package server;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.HashMap;
import java.util.Map;

import org.apache.cxf.frontend.ServerFactoryBean;
import org.apache.mina.common.ByteBuffer;
import org.apache.mina.common.IoAcceptor;
import org.apache.mina.common.SimpleByteBufferAllocator;
import org.apache.mina.filter.LoggingFilter;
import org.apache.mina.filter.codec.ProtocolCodecFilter;
import org.apache.mina.transport.socket.nio.SocketAcceptor;
import org.apache.mina.transport.socket.nio.SocketAcceptorConfig;

import rnClasses.RNBase;
import service.GenericWebServiceInvoker;
import service.IServiceGenericInvoker;
import client.LHClient;
import codec.LHCodecFactory;

public class LhSwingServer {
	private static final int PORT = 9123;
	
	private static final Map<String, Object> controllerMap = new HashMap<String, Object> ();
	
	public static Object getControllerObject (String controllerId){
		return controllerMap.get(controllerId);
	}
	
	public static void registerController (String controllerKey,Object controller){
		controllerMap.put(controllerKey, controller);
	}
	
	
	public LhSwingServer() throws IOException {
		deployWebService();
		startLhServer();
	}

	private void startLhServer() throws IOException {
		ByteBuffer.setUseDirectBuffers(false);
		ByteBuffer.setAllocator(new SimpleByteBufferAllocator());

		IoAcceptor acceptor = new SocketAcceptor();

		SocketAcceptorConfig cfg = new SocketAcceptorConfig();
		cfg.getFilterChain().addLast("logger", new LoggingFilter());
		cfg.getFilterChain().addLast(
				"codec",
				new ProtocolCodecFilter(new LHCodecFactory(false)));

		acceptor.bind(new InetSocketAddress(PORT), new LHServerHandler(), cfg);
		System.out.println("LH SERVER STARTED.");
	}

	private void deployWebService() {
		GenericWebServiceInvoker implementor = GenericWebServiceInvoker.getInstance();
		String address = "http://localhost:8080/genericWebServerInvoker";
		ServerFactoryBean svrFactory = new ServerFactoryBean();
        svrFactory.setServiceClass(IServiceGenericInvoker.class);
        svrFactory.setAddress(address);
        svrFactory.setServiceBean(implementor);
        svrFactory.create();
	}

	/**
	 * @param args
	 * @throws IOException
	 */
	public static void main(String[] args) throws IOException {
		new LhSwingServer();
		LhSwingServer.registerController("classe1", new RNBase());		
		new LHClient ();

	}

}
